package redisclient

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"time"
)

var ctx = context.Background()

type RedisClient struct {
	Client *redis.Client
}

func NewRedisClient(addr string, password string, db int) *RedisClient {
	rdb := redis.NewClient(&redis.Options{
		Addr:     addr,     // Redis地址
		Password: password, // Redis密码，没有则留空
		DB:       db,       // 默认数据库编号
	})

	return &RedisClient{Client: rdb}
}

func (c *RedisClient) Set(key string, value interface{}, expiration time.Duration) error {
	err := c.Client.Set(ctx, key, value, expiration).Err()
	if err != nil {
		return err
	}
	return nil
}

func (c *RedisClient) Get(key string) (string, error) {
	val, err := c.Client.Get(ctx, key).Result()
	if err == redis.Nil {
		return "", fmt.Errorf("key does not exist")
	} else if err != nil {
		return "", err
	}
	return val, nil
}

func (c *RedisClient) Del(keys ...string) error {
	err := c.Client.Del(ctx, keys...).Err()
	if err != nil {
		return err
	}
	return nil
}
